import { queryFiles, getSimpleFileInfo } from "@/api/files";
import { numToChinanumerals } from "chinesenum";

export async function downloadFile(row) {
  try {
    const res = await getSimpleFileInfo({
      uuidList: [{ fileUuid: row.fileUuid }],
    });
    const item = res.data[0];

    const ret = await queryFiles({
      fileId: item.fileUuid,
      modelKey: "original",
      timeStamp: new Date().getTime(),
    });

    const url = window.URL.createObjectURL(new Blob([ret]));
    const link = document.createElement("a");
    const fname = item.fileName + "." + item.fileType;
    link.href = url;
    link.setAttribute("download", fname);
    document.body.appendChild(link);
    link.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link); // 清理DOM元素
  } catch (error) {
    this.$message.error("下载文件出错");
  }
}

export async function previewFile(row) {
  try {
    const res = await getSimpleFileInfo({
      uuidList: [{ fileUuid: row.fileUuid }],
    });
    const item = res.data[0];

    const allowedFormats = ["docx", "pdf", "excel", "xlsx"];
    const pictureList = ["png", "jpg", "jpeg", "gif"];
    if (![...allowedFormats, ...pictureList].includes(item.fileType)) {
      throw new Error(
        `文件格式 ${item.fileType} 不被支持，请预览支持的格式如: ${[
          ...allowedFormats,
          ...pictureList,
        ].join(", ")}`
      );
    }

    const ret = await queryFiles({
      fileId: item.fileUuid,
      modelKey: "original",
      timeStamp: new Date().getTime(),
    });
    return {
      arrayBuffer: [...pictureList].includes(item.fileType)
        ? row.fileUuid
        : await ret.arrayBuffer(),
      fileType: item.fileType,
    };
  } catch (error) {
    throw error;
  }
}

// 金额转简体字大写
export function numToChinaNumerals(number) {
  return numToChinanumerals(number, { format: "MONEY" });
}

// 金额每3位以逗号分隔
export function formatMoney(money) {
  return Number(money).toLocaleString();
}
